package com.ruoyi.cms.utils;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.List;

@Slf4j
@Component("cmsdbutil")
public class CmsDbUtil {

    @Autowired
    DataSource dataSource;

    private Db db;

    /**
     * 列表
     * @param sql
     * @param params
     * @return
     */
    @SneakyThrows
    public List<Entity> select(String sql, Object... params) {
        log.debug("[CMSDB | SELECT] {} | {}", sql, params);
        return db.query(sql, params);
    }

    /**
     * 明细
     * @param sql
     * @param params
     * @return
     */
    @SneakyThrows
    public Entity selectOne(String sql, Object... params) {
        log.debug("[CMSDB | SELECTONE] {} | {}", sql, params);
        return db.queryOne(sql, params);
    }

    /**
     * 插入
     * @param sql
     * @param params
     * @return
     */
    @SneakyThrows
    public int insert(String sql, Object... params) {
        log.debug("[CMSDB | INSERT] {} | {}", sql, params);
        return db.execute(sql, params);
    }

    /**
     * 修改
     * @param sql
     * @param params
     * @return
     */
    @SneakyThrows
    public int update(String sql, Object... params) {
        log.debug("[CMSDB | UPDATE] {} | {}", sql, params);
        return db.execute(sql, params);
    }

    /**
     * 删除
     * @param sql
     * @param params
     * @return
     */
    @SneakyThrows
    public int delete(String sql, Object... params) {
        log.debug("[CMSDB | DELETE] {} | {}", sql, params);
        return db.execute(sql, params);
    }

    /**
     * 执行
     * @param sql
     * @param params
     * @return
     */
    @SneakyThrows
    public int execute(String sql, Object... params) {
        log.debug("[CMSDB | EXECUTE] {} | {}", sql, params);
        return db.execute(sql, params);
    }

    /**
     * 获取数据库
     * @return
     */
    public Db getDb() {
        return this.db;
    }

    @PostConstruct
    public void postConstruct () {
        this.db = Db.use(dataSource);
    }

}
